import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-04-20
 * Time: 19:01
 */
public class Sort {

    public static void InsertSort(int[] array) {

        for (int i = 0; i < array.length; i++) {
            int j = i - 1;
            int tmp = array[i];
            while (j >= 0) {
                if (array[j] > tmp) {
                    array[j + 1] = array[j];
                    j--;
                } else {
//                    array[j + 1] = tmp;
                    break;
                }
            }
            array[j + 1] = tmp;
        }
    }

    //希尔排序
    public static void ShellSort(int[] array) {
        int gap = array.length;
        while (gap > 1) {
            gap /= 2;
            shell(array, gap);
        }
    }

    private static void shell(int[] array, int gap) {
        for (int i = gap; i < array.length; i++) {
            int j = i - gap;
            int tmp = array[i];
            while (j >= 0) {
                if (array[j] > tmp) {
                    array[j + gap] = array[j];
                    j -= gap;
                } else {
//                    array[j + 1] = tmp;
                    break;
                }
            }
            array[j + gap] = tmp;
        }
    }

    private static void swap(int[] a, int x, int y) {
        int tmp = a[x];
        a[x] = a[y];
        a[y] = tmp;
    }

    //选择排序
    public static void SelectSort(int[] array) {
        for (int i = 0; i < array.length; i++) {
            int tmp = array[0];
            int minIndex = i;
            for (int j = i + 1; j < array.length; j++) {
                if (array[j] < array[minIndex]) {
                    minIndex = j;
                }
            }
            swap(array, minIndex, i);
        }
    }

    //堆排序
    public static void HeapSort(int[] array) {
        //先建大堆
        for (int parent = (array.length - 1 - 1) / 2; parent >= 0; parent--) {
            ShiftDown(parent, array, array.length);
        }
        int end = array.length - 1;
        while (end >= 0) {
            swap(array, 0, end);
            ShiftDown(0, array, end);
            end--;
        }
    }


    private static void ShiftDown(int parent, int[] array, int end) {
        int child = parent * 2 + 1;
        while (child < end) {
            if (child + 1 < end && array[child] < array[child + 1]) {
                child++;
            }
            if (array[child] > array[parent]) {
                swap(array, child, parent);
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;
            }
        }
    }

    public static void main(String[] args) {
        int[] a = {2, 9, 5, 1, 7, 4, 8, 6, 3, 5};
        System.out.println(Arrays.toString(a));
//        InsertSort(a);
//        ShellSort(a);
//        ShellSort(a);
        HeapSort(a);
        System.out.println(Arrays.toString(a));
    }

}
